package com.crazy.crazygateway.filter;

import com.crazy.crazycommon.common.ErrorCode;
import com.crazy.crazycommon.exception.BusinessException;
import com.crazy.crazycommon.properties.JwtProperties;
import com.crazy.crazycommon.utils.JWTUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

@Component
@Slf4j
public class GlobalAuthFilter implements GlobalFilter, Ordered {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 生成token用的私钥和过期时间
     */
    @Resource
    private JwtProperties jwtProperties;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        String path = serverHttpRequest.getURI().getPath();
        log.info("path = {}",path);
        // 如果登录或注册则放行
        if (antPathMatcher.match("/**/login", path) || antPathMatcher.match("/**/register", path) || antPathMatcher.match("/**/api-docs",path)) {
            return chain.filter(exchange);
        }
        // 判断路径中是否包含 inner，只允许内部调用
        if (antPathMatcher.match("/**/inner/**", path)) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.FORBIDDEN);
            DataBufferFactory dataBufferFactory = response.bufferFactory();
            DataBuffer dataBuffer = dataBufferFactory.wrap("无权限".getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(dataBuffer));
        }
        // 统一权限校验，通过 JWT 获取登录用户信息
        String token = serverHttpRequest.getHeaders().getFirst(jwtProperties.getTokenName());
        if (token != null && token.startsWith("Bearer ")) {
            try {
                token = token.substring(7);
                log.info("校验token:{}", token);
                // 解析token
                Claims claims = JWTUtils.parseJWT(jwtProperties.getSecretKey(), token);
                // 获取登录用户id
                Long adminID = Long.valueOf(claims.get("adminID").toString());
                log.info("token校验成功,adminID ={}", adminID);
            } catch (Exception e) {
                e.printStackTrace();
                ServerHttpResponse response = exchange.getResponse();
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                log.info("token解析错误，权限校验失败");
                return response.setComplete();
            }
        } else {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            log.info("token为空，权限校验失败");
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    /**
     * 优先级提到最高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
